package com.hiray.demos.glue

import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.hiray.demos.BR
import com.hiray.demos.R
import com.hiray.demos.databinding.ItemProfileBinding
import com.hiray.demos.model.ItemModel

/**
 * Created by hiray on 2018/5/31.
 *@author hiray
 */
class CrossAdapter(private var onItemClickListener: OnItemClickListener?) : androidx.recyclerview.widget.RecyclerView.Adapter<CrossAdapter.ItemViewHolder>() {

    private lateinit var layoutInflater: LayoutInflater
    var data: MutableList<ItemModel> = ArrayList()
        set(value) {
            field.clear()
            field.addAll(value)
            notifyDataSetChanged()
        }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        layoutInflater = LayoutInflater.from(parent.context)

        val binding = DataBindingUtil.inflate<ItemProfileBinding>(layoutInflater, R.layout.item_profile, parent, false)
        return ItemViewHolder(binding)

    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        holder.binding.setVariable(BR.model, data[holder.adapterPosition])
        holder.itemView.setOnClickListener({
            if (onItemClickListener != null)
                onItemClickListener?.onItemClick(it)
        })
    }

    class ItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
        lateinit var binding: ItemProfileBinding

        constructor(binding: ItemProfileBinding) : this(binding.root) {
            this.binding = binding
        }
    }

    interface OnItemClickListener {
        fun onItemClick(view: View)
    }
}